package io.knifer.gokexceltask.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import io.knifer.gokexceltask.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
    private final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private Map<String, List<String>> validateMsg;

    public LocalDateTimeConverter(){}

    public LocalDateTimeConverter(Map<String, List<String>> validateMsg){
        this.validateMsg = validateMsg;
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public WriteCellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(value.format(df));
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        LocalDateTime result;
        String stringValue = cellData.getStringValue();

        try{
            result = LocalDateTime.parse(stringValue, df);
        }catch (DateTimeParseException e){
            if (validateMsg == null){
                validateMsg = HttpUtils.getSessionAttr("validate_msg", Map.class);
            }

            String rowNum = cellData.getRowIndex().toString();
            List<String> errorMsg = validateMsg.getOrDefault(rowNum, new CopyOnWriteArrayList<>());

            errorMsg.add("日期【" + stringValue + "】格式错误（自动设置为当前时间）");
            validateMsg.put(rowNum, errorMsg);
            result = LocalDateTime.now();
        }

        return result;
    }
}
